﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.ApplicationServices;
using WlanDesign;
using Autodesk.AutoCAD.Interop;
using System.Runtime.InteropServices;

namespace WlanDesignDll
{
    public partial class FormAttributeSet : Form
    {
        //private static Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
        //private static Database acCurDb = acDoc.Database;
        public FormAttributeSet()
        {
            InitializeComponent();
        }

        private void FormAttributeSet_Load(object sender, EventArgs e)
        {
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            // ini文件与当前文档在同一目录下，并且名字相同
            string[] name = acDoc.Name.Split('.');
            string iniName = name[0] + ".ini";
            //图层设定
            string buildingLayer = ReadIniTxt(iniName, "layer", "building_layer");
            string[] AntennaLy = ReadIniTxt(iniName, "layer", "antenna_layer").Split(',');
            this.cBox_Building.DataSource = IterateLayers();
            this.lBox_Antenna.DataSource = IterateLayers();
            if (buildingLayer == "")
            {
                this.cBox_Building.SelectedIndex = 0;
            }
            else this.cBox_Building.Text = buildingLayer;
            if (AntennaLy.Count() == 0)
            {
                this.lBox_Antenna.SelectedIndex = 0;
            }
            else
            {
                this.lBox_Antenna.SelectedIndex = -1;
                this.lBox_Antenna.Text = AntennaLy[0];
            }
            //衰减度
            string penet0 = ReadIniTxt(iniName, "attenuation", "penetrance_attenuation");
            if (penet0 == "")
            {
                this.tBox_Penet.Text = "0";
            }
            else
            {
                this.tBox_Penet.Text = penet0;
            }
            //图纸比例
            string scale0 = ReadIniTxt(iniName, "scale", "drawing_scale");
            if (scale0 == "")
            {
                this.tBox_Scale.Text = "0";
            }
            else
            {
                this.tBox_Scale.Text = scale0;
            }
            /*
            //图纸修正
            string accuracy0 = ReadIniTxt(iniName, "threshold", "accuracy_threshold");
            if (accuracy0 == "")
            {
                this.tBox_Accuracy.Text = "0";
            }
            else
            {
                this.tBox_Accuracy.Text = accuracy0;
            }
             */
        }


        //
        // Summery
        // 获得所有图层
        //
        public static List<string> IterateLayers()
        {
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            // Get the current document and database, and start a transaction
            List<string> name = new List<string>();

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // This example returns the layer table for the current database
                LayerTable acLyrTbl;
                acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
                                             OpenMode.ForRead) as LayerTable;

                // Step through the Layer table and print each layer name              
                foreach (ObjectId acObjId in acLyrTbl)
                {
                    LayerTableRecord acLyrTblRec;
                    acLyrTblRec = acTrans.GetObject(acObjId,
                                                    OpenMode.ForRead) as LayerTableRecord;

                    name.Add(acLyrTblRec.Name);
                }

                // Dispose of the transaction
            }
            return name;
        }

        //
        // Summery
        // 加载信息到ini文件
        //
        public void WriteIniTxt(string sPath, string Section, string Key, string value)
        {
            string ServerName = value;

            IniFileRW ini = new IniFileRW(sPath);

            ini.IniWriteValue(Section, Key, ServerName);
        }

        //
        // Summery
        // 从ini文件读取信息
        //
        public static string ReadIniTxt(string sPath, string Section, string Key)
        {
            string ServerName;
            IniFileRW ini = new IniFileRW(sPath);
            ServerName = ini.IniReadValue(Section, Key);
            string strSql = ServerName;
            return strSql;
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            if (acDoc.Name.Split('\\').Count() >= 2)
            {
                // ini文件与当前文档在同一目录下，并且名字相同
                string[] name = acDoc.Name.Split('.');
                string iniName = name[0] + ".ini";

                //
                // 获得建筑物图层的选项
                if (this.cBox_Building.SelectedIndex >= 0)
                {
                    string buildLyr = this.cBox_Building.SelectedItem.ToString();

                    if (this.lBox_Antenna.SelectedIndex >= 0)
                    {

                        // 获得天线图层的选项，做成“ZN-天线,ZN-功分器,…”字符串
                        string antLyr = null;

                        for (int i = 0; i < this.lBox_Antenna.SelectedItems.Count - 1; i++)
                        {
                            antLyr += this.lBox_Antenna.SelectedItems[i].ToString() + ",";
                        }

                        antLyr += this.lBox_Antenna.SelectedItems[this.lBox_Antenna.SelectedItems.Count - 1]
                            .ToString();
                        // 写入ini文件
                        WriteIniTxt(iniName, "layer", "building_layer", buildLyr);
                        WriteIniTxt(iniName, "layer", "antenna_layer", antLyr);

                        //
                        // 衰减度设定
                        string penet = this.tBox_Penet.Text;
                        if (isNumberic(penet))
                        {
                            string[] name1 = acDoc.Name.Split('.');
                            string iniName1 = name1[0] + ".ini";
                            // 写入ini文件
                            WriteIniTxt(iniName1, "attenuation1", "penetrance_attenuation1", penet);//临时存放，方便与上次的进行比较

                            Autodesk.AutoCAD.Interop.AcadApplication acAppComObj = null;
                            const string strProgId = "AutoCAD.Application.18";
                            // Get a running instance of AutoCAD
                            try
                            {
                                acAppComObj = (AcadApplication)Marshal.GetActiveObject(strProgId);
                            }
                            catch // An error occurs if no instance is running
                            {
                                try
                                {
                                    // Create a new instance of AutoCAD
                                    acAppComObj = (AcadApplication)Activator.CreateInstance(Type.GetTypeFromProgID(strProgId), true);

                                }
                                catch
                                {
                                    // If an instance of AutoCAD is not created then message and exit
                                    System.Windows.Forms.MessageBox.Show("Instance of 'AutoCAD.Application'" + " could not be created.");
                                    return;
                                }
                            }
                            AcadDocument acDocComObj;

                            acDocComObj = acAppComObj.ActiveDocument;
                            acDocComObj.SendCommand("AttenuationSet ");
                            //WriteIniTxt(iniName1, "attenuation1", "penetrance_attenuation1", "");
                            // 写入ini文件
                            WriteIniTxt(iniName, "attenuation", "penetrance_attenuation", penet);

                            //
                            // 图纸比例
                            string scale = this.tBox_Scale.Text;
                            if (isNumberic(scale))
                            {
                                WriteIniTxt(iniName, "scale", "drawing_scale", scale);

                                /*
                                //
                                // 图纸修正
                                string accuracy = this.tBox_Accuracy.Text;
                                if (isNumberic(accuracy))
                                {
                                    WriteIniTxt(iniName, "threshold", "accuracy_threshold", accuracy);
                                 */
                                    MessageBox.Show("属性参数已保存到：\n" + iniName);
                                /*
                                    // MessageBox.Show("保存成功！");
                                }
                                else
                                {
                                    MessageBox.Show("修正阈值格式不正确！");
                                }
                                 */
                            }
                            else
                            {
                                MessageBox.Show("图纸比例格式不正确！");
                            }
                        }
                        else
                        {
                            MessageBox.Show("衰减度格式不正确！");
                        }
                    }

                    else
                    {
                        MessageBox.Show("天线图层不能为空！");
                    }
                }
                else
                {
                    MessageBox.Show("建筑物图层不能为空！");
                }
            }
            else
            {
                MessageBox.Show("请先保存图纸！");
            }
        }

        /*
        private void btn_Repair_Click(object sender, EventArgs e)
        {
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            // ini文件与当前文档在同一目录下，并且名字相同
            string[] name = acDoc.Name.Split('.');
            string iniName = name[0] + ".ini";
            string accuracy = this.tBox_Accuracy.Text;

            WriteIniTxt(iniName, "threshold", "accuracy_threshold", accuracy);
            if (acDoc.Name.Split('\\').Count() >= 2)
            {
                string threshold = this.tBox_Accuracy.Text;
                if (threshold == "")
                {
                    MessageBox.Show("阈值不能为空，请输入阈值！");
                    return;
                }
                if (isNumberic(threshold))
                {
                    string LayerBuild = ReadIniTxt(iniName, "layer", "building_layer");
                    string Atten = ReadIniTxt(iniName, "attenuation", "penetrance_attenuation");
                    if (LayerBuild == "" || Atten == "" || !isNumberic(Atten))
                    {
                        MessageBox.Show("请先进行属性设置！");
                        return;
                    }
                    else
                    {
                        string scale = ReadIniTxt(iniName, "scale", "drawing_scale");
                        double rate = Convert.ToDouble(scale);//比例因子
                        //string threshold = WlanDesign.FormStartup.ReadIniTxt(iniName, "threshold", "accuracy_threshold");//读取用户设置的精度阈值
                        //if (!isNumberic(threshold))
                        //{
                        //MessageBox.Show("精度阈值必须为数字，请设置正确的精度阈值，如10");
                        //return;
                        //}
                        double threshold_1 = Convert.ToDouble(threshold);//将读取的阈值转换为double类型的
                        if (threshold_1 / rate > 0.05)
                        {
                            MessageBox.Show("请检查精度阈值或比例因子设置是否正确！");
                            return;
                        }
                        else
                        {
                            AcadApplication acAppComObj = null;
                            const string strProgId = "AutoCAD.Application.18";
                            // Get a running instance of AutoCAD
                            try
                            {
                                acAppComObj = (AcadApplication)Marshal.GetActiveObject(strProgId);
                            }
                            catch // An error occurs if no instance is running
                            {
                                try
                                {
                                    // Create a new instance of AutoCAD
                                    acAppComObj = (AcadApplication)Activator.CreateInstance(Type.GetTypeFromProgID(strProgId), true);

                                }
                                catch
                                {
                                    // If an instance of AutoCAD is not created then message and exit
                                    System.Windows.Forms.MessageBox.Show("Instance of 'AutoCAD.Application'" + " could not be created.");
                                    return;
                                }
                            }
                            AcadDocument acDocComObj;
                            acDocComObj = acAppComObj.ActiveDocument;
                            acDocComObj.SendCommand("DrawingRepair ");
                           
                            // 图纸修正
                            //string[] name = acDoc.Name.Split('.');
                            //string iniName = name[0] + ".ini";
                            //string accuracy = this.tBox_Accuracy.Text;

                            //WriteIniTxt(iniName, "threshold", "accuracy_threshold", accuracy);
                            //MessageBox.Show("已完成修正！");
                        }
                    }
                }
                else
                {
                    MessageBox.Show("修正阈值格式不正确！");
                }
            }
            else
            {
                MessageBox.Show("请先保存图纸！");
            }
        }
         */

        private void btn_Undo_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        /// <summary>
        /// 判断字符串是否为数字
        /// </summary>
        public static bool isNumberic(string message)
        {
            System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(@"^(-?\d+)(\.\d+)?$");
            if (rex.IsMatch(message))
            {
                return true;
            }
            else
                return false;
        }
        
        private void tBox_Accuracy_Validating(object sender, CancelEventArgs e)
        {/*
            if (this.tBox_Accuracy.Text == "")
            {
                this.btn_Repair.Enabled = false;
            }
            else if (Convert.ToDouble(this.tBox_Accuracy.Text) <= 0)
            {
                this.btn_Repair.Enabled = false;
            }
            else
            {
                this.btn_Repair.Enabled = true;
            }*/
        }
         
        /*
        private void tBox_Accuracy_TextChanged(object sender, EventArgs e)
        {
            if (this.tBox_Accuracy.Text == "")
            {
                this.btn_Repair.Enabled = false;
            }
            else if (!isNumberic(this.tBox_Accuracy.Text))
            {
                this.btn_Repair.Enabled = false;
            }
            else if (Convert.ToDouble(this.tBox_Accuracy.Text) <= 0)
            {
                this.btn_Repair.Enabled = false;
            }
            else
            {
                this.btn_Repair.Enabled = true;
            }
        }
         */
    }
}
